import json

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views import View
from django.http import JsonResponse
from constr_budgets.models import People, Position


class UserList(View):
    def post(self, req):
        d = json.loads(req.body)
        print(json.loads(req.body))
        user = People.objects.filter(phone=d['phone'])
        if user:
            return JsonResponse({"code": 500, "msg": "手机号已存在"})
        else:
            People.objects.create(name=d["name"], phone=d["phone"], password=d["password"], people_id=d["people_id"],
                              peopleState=d["peopleState"])
        return JsonResponse({"code": 200, "msg": "添加成功"})

    def get(self, req):
        page = req.GET.get('page')
        page_size = req.GET.get('pagesize')
        username = req.GET.get('username')
        people_list = list(People.objects.all().values())
        paginator = Paginator(people_list, page_size)
        total = paginator.count
        try:
            users = paginator.page(page)
        except PageNotAnInteger:
            # 执行分页查询,默认指定页码
            users = paginator.page(1)
        except EmptyPage:
            users = paginator.page(paginator.num_pages)
        role = list(Position.objects.all().values())
        if username:
            users = People.objects.filter(name__contains=username).values()
        return JsonResponse({"code": 200, "msg": "获取成功", "data": list(users), "total": total, "role": role})

    def put(self, req):
        d = json.loads(req.body)
        if int(d["id"]) == 1:
            return JsonResponse({"code": 401, "msg": "超级管理员不能进行操作"})
        else:
            People.objects.filter(phone=d["pho"]).update(phone=d["phone"], name=d["name"], password=d["password"],people_id=d["people_id"], peopleState=d["peopleState"])
            return JsonResponse({"code": 200, "msg": "修改成功"})

    def delete(self, req):
        d = req.GET.get("phone")
        People.objects.filter(phone=d).delete()
        return JsonResponse({"code": 200, "msg": "删除成功"})

    def patch(self, req):
        try:
            d = json.loads(req.body)
            People.objects.filter(phone=d["phone"]).update(people_id=d['role_id'])
            return JsonResponse({"code": 200, "msg": "分配角色成功"})
        except django.db.utils.IntegrityError:
            return JsonResponse({"code": 401, "msg": "请选择角色"})
